import { FC, useCallback, useEffect } from "react";
import { Form, Input, Button, Checkbox, Col, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";

import { withRouter, RouteComponentProps } from "react-router";

import "./index.scss";
import http from "@/component/http";
import store from "@/store";
import { setUserInfo } from "@/store/actions/setUserInfo";

/*登录
 */
const Login: FC<RouteComponentProps> = (props) => {
  interface Ivalue {
    username: string;
    password: string;
    remember: boolean;
  }
  const toHome = useCallback(() => {
    props.history.push("/");
  },[props.history]);

  useEffect(() => {
    if (localStorage.getItem("userInfo")) {
      toHome();
    }
  }, [toHome]);

  const onFinish = (values: Ivalue) => {
    http.get("login.json", values).then((res: any) => {
      localStorage.setItem("userInfo", JSON.stringify(res.resRecord));
      store.dispatch(setUserInfo(res.resRecord));
      if (res.resCode === "000000") {
        message.success({
          content: res.resMsg,
        });
        toHome();
      } else {
        message.error({
          content: res.resMsg || "登陆失败",
        });
      }
    });
  };

  return (
    <div className="login-container">
      <div className="login-banner"></div>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Col style={{ padding: "20px", fontSize: "18px" }}>星火管理平台</Col>

        <Form.Item
          name="username"
          rules={[{ required: true, message: "Please input your Username!" }]}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="  请输入账号"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "Please input your Password!" }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="  请输入密码"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "Please input your Password!" }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="  请输入密码"
          />
        </Form.Item>
        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
          <a className="login-form-forgot" href="/404">
            注册账号
          </a>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default withRouter(Login);
